import 'package:flutter/material.dart';
import '../xapp_utils.dart';

class LoadingDialogUtils {
  static LoadingDialogUtils? _instance;

  static LoadingDialogUtils getInstance() {
    if (_instance == null) {
      _instance = new LoadingDialogUtils._();
    }
    return _instance!;
  }

  Route? route;

  LoadingDialogUtils._();

  // 显示loading，全局只能显示一个
  void show({String msg = '请稍后'}) {
    if (route != null) {
      return;
    }
    route = _LoadingDialogRouter(_LoadingDialog(msg));
    Navigator.of(XAppUtils.getInstance().getContext()).push(route!);
  }

  // 隐藏loading
  void hide() {
    if (route != null) {
      Navigator.of(XAppUtils.getInstance().getContext()).removeRoute(route!);
      route = null;
    }
  }
}

// loading widget
class _LoadingDialog extends Dialog {
  final String msg;

  const _LoadingDialog(this.msg)
      : super(
          clipBehavior: Clip.none,
        );

  @override
  Widget build(BuildContext context) {
    print(this);
    return WillPopScope(
      child: Material(
        type: MaterialType.transparency,
        child: Center(
          child: Container(
            width: 100.rpx,
            height: 100.rpx,
            decoration: BoxDecoration(
              color: rgba(0, 0, 0, 0.8),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Column(
              children: <Widget>[
                Padding(
                  child: CircularProgressIndicator(
                    strokeWidth: 2.rpx,
                    color: Theme.of(context).primaryColor,
                  ),
                  padding: EdgeInsets.only(
                      left: 30.rpx, right: 30.rpx, top: 25.rpx, bottom: 10.rpx),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
                  child: Text(
                    msg,
                    style: TextStyle(
                        color: Colors.white, fontSize: 11.rpx, height: 1.5),
                    maxLines: 1,
                    overflow: TextOverflow.clip,
                  ),
                )
              ],
            ),
          ),
        ),
      ),
      onWillPop: () async {
        return false;
      },
    );
  }
}

// loading路由
class _LoadingDialogRouter extends PageRouteBuilder {
  final Widget page;

  _LoadingDialogRouter(this.page)
      : super(
          opaque: false,
          barrierColor: Color(0x00000001),
          pageBuilder: (context, animation, secondaryAnimation) => page,
          transitionsBuilder: (context, animation, secondaryAnimation, child) =>
              child,
        );
}
